<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    width="500px"
    modal
    class="dialog-layout"
    modal-append-to-body
    append-to-body
    lock-scroll
    show-close
    :close-on-click-modal="false"
  >
    <el-tabs v-model="activeTag">
      <el-tab-pane
        :label="L('UserDetails')"
        name="first"
      >
        <el-form
          ref="userForm"
          v-loading="loading"
          label-width="80px"
          :model="editUser"
          :rules="fromRoles"
        >
          <el-form-item
            :label="L('UserName')"
            prop="userName"
          >
            <el-input
              v-model="editUser.userName"
              :maxlength="32"
              :minlength="2"
            />
          </el-form-item>
          <el-form-item
            :label="L('Name')"
            prop="name"
          >
            <el-input
              v-model="editUser.name"
              :maxlength="32"
            />
          </el-form-item>
          <el-form-item
            :label="L('Surname')"
            prop="surname"
          >
            <el-input
              v-model="editUser.surname"
              :maxlength="1024"
            />
          </el-form-item>
          <el-form-item
            :label="L('EmailAddress')"
            prop="emailAddress"
          >
            <el-input
              v-model="editUser.emailAddress"
              :maxlength="32"
            />
          </el-form-item>
          <el-form-item
            v-if="action == 'create'"
            :label="L('Password')"
            prop="password"
          >
            <el-input
              v-model="editUser.password"
              type="password"
              :maxlength="32"
            />
          </el-form-item>
          <el-form-item
            v-if="action == 'create'"
            :label="L('ConfirmPassword')"
            prop="confirmPassword"
          >
            <el-input
              v-model="editUser.confirmPassword"
              type="password"
              :maxlength="32"
            />
          </el-form-item>
          <el-form-item>
            <el-checkbox v-model="editUser.isActive">{{ L('IsActive') }}</el-checkbox>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane
        :label="L('UserRoles')"
        name="second"
      >
        <el-checkbox-group v-model="editUser.roleNames">
          <el-checkbox
            v-for="role in roles"
            :key="role.id"
            :label="role.normalizedName"
          ><span>{{ role.name }}</span></el-checkbox>
        </el-checkbox-group>
      </el-tab-pane>
    </el-tabs>

    <div slot="footer">
      <el-button @click="close">{{ L('Cancel') }}</el-button>
      <el-button
        type="primary"
        @click="save"
      >{{ L('OK') }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  data() {
    const validatePassCheck = (rule, value, callback) => {
      if (!value) {
        callback(new Error('Please enter your password again'))
      } else if (value !== this.editUser.password) {
        callback(new Error('The two input passwords do not match!'))
      } else {
        callback()
      }
    }
    return {
      visible: false,
      loading: false,
      action: '',
      activeTag: 'first',
      editUser: {},
      userRule: {
        userName: [
          { required: true, message: this.L('FieldIsRequired', undefined, this.L('UserName')), trigger: 'blur' }
        ],
        name: [
          { required: true, message: this.L('FieldIsRequired', undefined, this.L('Name')), trigger: 'blur' }
        ],
        surname: [
          { required: true, message: this.L('FieldIsRequired', undefined, this.L('Surname')), trigger: 'blur' }
        ],
        emailAddress: [
          { required: true, message: this.L('FieldIsRequired', undefined, this.L('Email')), trigger: 'blur' },
          { type: 'email' }
        ]
      },
      newUserRule: {
        userName: [
          { required: true, message: this.L('FieldIsRequired', undefined, this.L('UserName')), trigger: 'blur' }
        ],
        name: [
          { required: true, message: this.L('FieldIsRequired', undefined, this.L('Name')), trigger: 'blur' }
        ],
        surname: [
          { required: true, message: this.L('FieldIsRequired', undefined, this.L('Surname')), trigger: 'blur' }
        ],
        emailAddress: [
          { required: true, message: this.L('FieldIsRequired', undefined, this.L('Email')), trigger: 'blur' },
          { type: 'email' }
        ],
        password: [
          { required: true, message: this.L('FieldIsRequired', undefined, this.L('Password')), trigger: 'blur' }
        ],
        confirmPassword: { validator: validatePassCheck, trigger: 'blur' }
      }
    }
  },
  computed: {
    title() {
      return this.action === 'create' ? this.L('CreateNewUser') : this.L('EditUser')
    },
    roles() {
      // 打开user界面已经初始化过了
      return this.$store.state.user.roles
    },
    fromRoles() {
      return this.action === 'edit' ? this.userRule : this.newUserRule
    }
  },
  methods: {
    open(args, action) {
      this.$nextTick(function() {
        this.action = action
        this.editUser = JSON.parse(JSON.stringify(args))
        this.$nextTick(function() {
          this.$refs.userForm.clearValidate()
        })
      })

      return new Promise((resolve, reject) => {
        this.visible = true
        resolve()
      })
    },
    close() {
      return new Promise((resolve, reject) => {
        this.visible = false
        resolve()
      })
    },
    async save() {
      console.log(this.editUser)
      if (!!this.editUser.id && this.action === 'edit') {
        this.$refs.userForm.validate(async val => {
          if (val) {
            this.loading = true
            await this.$store.dispatch({
              type: 'user/update',
              data: this.editUser
            })
            this.loading = false
            this.$message({
              type: 'success',
              message: this.L('SavedSuccessfully')
            })
            this.$emit('save-success')
            this.close()
          }
        })
      } else {
        this.$refs.userForm.validate(async val => {
          if (val) {
            this.loading = true
            await this.$store.dispatch({
              type: 'user/create',
              data: this.editUser
            })
            this.loading = false
            this.$emit('save-success')
            this.close()
          }
        })
      }
    }
  }
}
</script>

<style>
</style>
